<!DOCTYPE html>
<html><head>
    <style>
        #content{width:600px;height:200px;}
    </style>
    <meta charset="utf-8">
</head>
<body id="body">
<textarea id="content" rows="40" cols="500"></textarea>
<div class="btn">
    <input type="button" value="清空" onclick="reset()">
    <input type="button" value="发送" onclick="send()">
</div>
<script type="text/javascript">

    let href = location.href;
    let strings = href.split("/");
    console.log(strings)
    let path = "ws://"+strings[2]+"/shop-api/demo01"
    console.log(path)

    let user = href.split("?")[1];
    console.log(user)

    var socket = new WebSocket("ws://localhost:8090/shop-api/WS/"+user);

    //错误出现在nginx代理上

    // ws://localhost:80/shop-api/demo01
    // ws://localhost:8090/shop-api/demo01
    // ws://location/shop-api/demo01

    //创建Socket
    socket.onopen = function(event) {

        //接收数据事件
        socket.onmessage = function(event) {
            let data = JSON.parse(event.data)
            console.log(data)
            body.innerHTML+="<br/>"+data.sender+"："+data.message;
        };

        // socket关闭事件
        socket.onclose = function(event) {
            body.innerHTML+="<br/>系统：已和服务器断开连接！！！";
        };

        socket.onerror = function (ev) {
            console.log("错误")
            console.log(ev.data)
        }


        //关闭socket
        //socket.close()
    };









    //-----------
    var body=document.getElementById("body");
    function send(){
        var msg=document.getElementById("content").value;//获取输入框内容
        socket.send(msg);//发送消息
        reset();//清空输入框
        body.innerHTML+="<br/>我："+msg;
    }

    function reset(){
        document.getElementById("content").value="";
    }
</script>

</html>